<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
	<meta charset="utf-8">
	<th:block th:include="include :: header('数据库数据管理')" />
</head>
<body class="gray-bg">
<div class="ui-layout-center">
     <div class="container-div">
		<div class="row">
		
				<div class="col-sm-12 search-collapse">
					<form id="user-form">
						<div class="select-list">
							<ul>
							<!-- 
								<li>
									字段名称：<input type="text" name="protoKey"/>
								</li>
								<li>
									比较类型：<select name="oprType">
												<option value="eq">等于</option>
												<option value="gt">大于</option>
												<option value="lt">小于</option>
												<option value="ge">大于等于</option>
												<option value="le">小于等于</option>
												<option value="between">区间</option>
											</select>
								</li>
								<li>
									字段值：<input type="text" placeholder="起始值" name="valOfKey"/>
									<span>-</span>
									<input type="text" placeholder="结束值" name="endValOfKey"/>
								</li>
							-->
								<li>
									数据表名称：
											<select name="protoName" id="protoNameSelect">
												<option value="">请选择数据表名</option>
												<!-- 
												<option th:each="protoMap : ${protoNameList}" th:text="${protoMap.key}" th:value="${protoMap.key}" th:class="${protoMap.value}"></option>
												 -->
												<option th:each="protoMap : ${protoTablesMapResult}" th:value="${protoMap.key}" th:text="${protoMap.value[0]}" th:class="${protoMap.value[1]}"></option>
											</select>
								</li>
								<li class="select-time">
									<label>请求时间： </label>
									<input type="text" class="time-input" id="startTime" data-format="yyyy-MM-dd HH:mm:ss" data-type="datetime" placeholder="开始时间" name="startTime"/>
									<span>-</span>
									<input type="text" class="time-input" id="endTime" data-format="yyyy-MM-dd HH:mm:ss" data-type="datetime" placeholder="结束时间" name="endTime"/>
								</li>
								<li>
									<a class="btn btn-warning btn-rounded btn-sm" onclick="tableOutput()"><i class="fa fa-upload"></i>&nbsp;表数据导出</a>
								</li>
								<li>
									<a class="btn btn-info btn-rounded btn-sm" onclick="tableInput()"><i class="fa fa-download"></i>&nbsp;表数据导入</a>
								</li>							
							</ul>
						</div>
			            <div class="row">
			                <div class="col-sm-12">
			                    <button type="button" class="btn btn-white btn-sm" onclick="addRow()"><i class="fa fa-plus"> 增加条件</i></button>
			                    <button type="button" class="btn btn-white btn-sm" onclick="sub.delRow()"><i class="fa fa-minus"> 删除条件</i></button>
			                    <div class="col-sm-12 select-table table-striped">
								    <table id="bootstrap-table2"></table>
								</div>
			                </div>
			            </div>
			            <br>
			            <a class="btn btn-primary btn-rounded btn-sm" onclick="$.table.searchForDataManage()"><i class="fa fa-search"></i>&nbsp;搜索</a>
						<a class="btn btn-warning btn-rounded btn-sm" onclick="resetPre()"><i class="fa fa-refresh"></i>&nbsp;重置</a>
					</form>
				</div>
				
			<div class="col-sm-12 select-table table-striped">
			    <!-- 点击事件的方式打开使用 detailViewIcon: false and detailViewByClick: true
			         data-detail-view-icon="false" 
			         data-detail-view-by-click="true" -->
				<table id="bootstrap-table"></table>
			</div>
		</div>
	</div>
</div>
<div id="tempDiv" style="display:none"></div>
<!-- 
<div id="tempMegment">
	<select class='form-control' name=''>
	    <option value="">请先选择协议名称</option>
	</select>
</div 
-->
    <div th:include="include :: footer"></div>
    <script th:src="@{/js/jquery.tmpl.js}"></script>

    <script th:inline="javascript">
    
    	var ipm = "127.0.0.1";
    
        $(function() {  	
            var options = {
                url: "/data/databaseList",
		        showSearch: false,
		        showRefresh: false,
		        showToggle: false,
		        showColumns: false,
		        //detailView: true,
		        pageSize: 10,
		        /**
				onExpandRow : function(index, row, $detail) {
					initChildTable(index, row, $detail);
				},
				**/
                columns: [{
		            field: 'id',
		            title: '数据ID'
		        },
		        {
		            field: 'protoName',
		            title: '协议名称'
		        },
		        {
		            field: 'protoDataNum',
		            title: '字段个数'
		        },
		        {
		            field: 'protoDataSize',
		            title: '协议体内容长度'
		        },
		        {
		            field: 'reqTime',
		            title: '请求时间',
		            sortable: true
		        },
		        {
		            field: 'inserttime',
		            title: '入库时间',
		            sortable: true
		        },
		        {
		            field: 'expireDate',
		            title: '过期时间',
		            sortable: true
		        },
		        {
		            field: 'protoData',
		            title: '子数据',
		            visible: false
		            
		        }]
            };
            $.table.init(options);
        });
        
        function getSecondQuery(tableName,fieldName,parentId){
        	//alert(tableName+"=="+"fieldName"+"=="+parentId);
        	$.modal.open(fieldName+"子表数据", "data/secondQueryPage?tableName="+tableName+"&fieldName="+fieldName+"&parentId="+parentId);
        }

        function getMyCustomField(tableName) {
        	var myColumns = [];
        	var segmentList = $("#protoNameSelect").children('option:selected').attr('class');
        	// 加载动态表格
        	$.ajax({
        		url: "/data/getCustomField",
	            data: {
	            	"tableName" : tableName,
	            	"segmentList" : segmentList
	            },
	            type: "post",
        		dataType : "json",
        		async : false,
        		success : function(returnValue) {
        			//console.log(returnValue)
        			
        			
        			$.each(returnValue, function(key, values) {
    					myColumns.push({
    						"field" : key,
    						"title" : values,
    						"hide" : true,
    						"align" : 'center',
    						"valign" : 'middle'
    							
    					});
    				});
        			
        			//console.log(myColumns);
        			
        		}
        	});
        	
        	return myColumns;
        }
        
		initChildTable = function(index, row, $detail) {
			var childTable = $detail.html('<table style="table-layout:fixed"></table>').find('table');
    	    $(childTable).bootstrapTable({
    	        data: row.protoData,
    	        detailView: true,
				onExpandRow : function(index, row, $detail) {
					initChildTableSeconde(index, row, $detail);
				},
    	        columns: [{
					field : 'id', 
					title : '数据ID',
		            visible: false
				},{
		        	field: 'index',
		        	align: 'center',
		        	title: "序号",
		        	width: "150px",
		        	//visible: false,
                    formatter: function (value, row, index) {
                    	return index + 1;
                    }
				},
				{
					field : 'protoKey', 
					title : '字段名称'
				},
				{
					field : 'protoValue', 
					title : '字段值'
				}]
    	    });
		};
		
		initChildTableSeconde = function(index, row, $detail) {
			var childTableSeconde = $detail.html('<table style="table-layout:fixed"></table>').find('table');
    	    $(childTableSeconde).bootstrapTable({
    	        url: "/data/databaseListSecond",
    	        method: 'post',
    	        sidePagination: "server",
    	        contentType: "application/x-www-form-urlencoded",
    	        queryParams : {
                    id: row.id
				},
    	        columns: [{
					field : 'id', 
					title : '数据ID',
		            visible: false
				},
				{
					field : 'protoKey', 
					title : '字段名称'
				},
				{
					field : 'protoValue', 
					title : '字段值'
				}]
    	    });
		};
		
		/* 自定义重置-表单重置/隐藏框/树节点选择色/搜索 */
		function resetPre() {
			resetDate();
			$("#user-form")[0].reset();
			$.table.search();
		}
		
		function getQueryTable() {
	    	var data = [
	    	{
	    		protoKey: "",
	    		oprType: "eq",
	    		valOfKey: "ddd",
	    		endValOfKey: ""
	    	},{
	    		protoKey: "",
	    		oprType: "gt",
	    		valOfKey: "aaa",
	    		endValOfKey: ""
	    	}];
		    var options = {
		    	//data: data,
                id:"bootstrap-table2",
                pagination: false,
		        showSearch: false,
                showRefresh: false,
                showToggle: false,
                showColumns: false,
                sidePagination: "client",
		        columns: [{
		            checkbox: true
		        },
		        {
		        	field: 'index',
		        	align: 'center',
		        	title: "序号",
		        	//visible: false,
                    formatter: function (value, row, index) {
                    	var columnIndex = $.common.sprintf("<input type='hidden' name='index' value='%s'>", $.table.serialNumberForProto(index,"bootstrap-table2"));
                    	var columnId = $.common.sprintf("<input type='hidden' name='composeCompare[%s].id' value='%s'>", index, row.id);
                    	return columnIndex + $.table.serialNumberForProto(index,"bootstrap-table2") + columnId;
                    }
                },
		        {
		            field: 'protoKey',
		            align: 'center',
		            title: '字段名称',
		            formatter: function(value, row, index) {
		            	//var html = $.common.sprintf("<input class='form-control goodsName' type='text' name='composeCompare[%s].protoKey' value='%s'>", index, value);
		        		//return html;
		        		
		        		var data = [{ index: index, type: value }];
		        		//composeCompare[${index}].oprType
		        		$("#tempDiv").html($("#keyContent").html());
		        		$("#tempDiv").find("select").find("option[value='"+value+"']").attr("selected","true");
		        		$("#tempDiv").find("select").attr("name","composeCompare["+index+"].protoKey");
		                //return $("#keyContent").tmpl(data).html();
		                return $("#tempDiv").html();
		                /**
		                $("#tempMegment").find("select").attr("name","composeCompare["+index+"].protoKey");
		                if(value != ""){
		                	$("#tempMegment").find("select").find("option[text='"+value+"']").attr("selected",true);
		                }
		                //$("#tempMegment").find("select").attr("id","tempIdSele");
		                //$("#tempIdSele option[value='fasf']").prop("selected", true);
		                if(value != ""){
		                	var maxIndex=$("#tempIdSele option:[value='"+value+"']");
			                alert(maxIndex.html());
		                }
		                
		                $("#tempMegment").find("select").attr("id","");
		                return $("#tempMegment").html();
		                **/
                    }
		        },
		        {
		            field: 'oprType',
		            align: 'center',
		            title: '比较类型',
		            formatter: function(value, row, index) {
		        		var data = [{ index: index, type: value }];
		                return $("#oprType").tmpl(data).html();
                    }
		        },
		        {
		            field: 'valOfKey',
		            align: 'center',
		            title: '字段值1',
		            formatter: function(value, row, index) {
		            	var html = $.common.sprintf("<input class='form-control' type='text' name='composeCompare[%s].valOfKey' value='%s'>", index, value);
		        		return html;
                    }
		        },
		        {
		            field: 'endValOfKey',
		            align: 'center',
		            title: '字段值2',
		            formatter: function(value, row, index) {
		            	var html = $.common.sprintf("<input class='form-control' type='text' name='composeCompare[%s].endValOfKey' value='%s'>", index, value);
		        		return html;
                    }
		        }]
		    };
		    $.table.init(options);
	    }
        
        function addRow() {
        	
        	var protoNameSelectValue = $("#protoNameSelect").val();
        	
        	if(protoNameSelectValue == ""){
        		$.modal.alertWarning("请先选择协议名称再添加字段条件！");
        		return;
        	}
        	
        	var count = $("#" + table.options.id).bootstrapTable('getData').length;
        	var row = {
                index: $.table.serialNumberForProto(count,"bootstrap-table2"),
                protoKey: "",
                oprType: "",
                valOfKey: "",
                endValOfKey: ""
            }
        	table.set('bootstrap-table2');
        	var count = $("#bootstrap-table2").bootstrapTable('getData').length;
        	sub.editRowForProto('bootstrap-table2');
        	$("#bootstrap-table2").bootstrapTable('insertRow', { index: count + 1, row: row });
        }
        
    	$(function() {
    		//初始化查询表格
    		getQueryTable();
    		$('#protoNameSelect').change(function(){  
    		　　var segmentList = $(this).children('option:selected').attr('class');
    			$.table.destroy("bootstrap-table2"); 
    			getQueryTable();
    			$('#bootstrap-table2').bootstrapTable('refresh', {silent: true});
    			//$.table.init(options);
    			 
    		　　　//发送AJAX请求
    		   	 $.ajax({
		            url: "/data/getProtoSegment",
		            data: {
		            	"segmentList" : segmentList
		            },
		            type: "post",
		            success: function(resultMap) {
		            	/**
		                if(resultList != null){
		                	$("#tempMegment").find("select").empty();
		                	$("#tempMegment").find("select").append("<option value=''>请选择字段</option>");
		                	//$(".myMegment").empty();
		                	//$(".myMegment").append("<option value=''>请选择字段</option>")
		                	//遍历List
		                	for(var index in resultList){
		                		//var megment = resultList[index];
		                		//$(".myMegment").append("<option value='"+resultList[index]+"'>"+resultList[index]+"</option>")
		                		$("#tempMegment").find("select").append("<option value='"+resultList[index]+"'>"+resultList[index]+"</option>");
		                	    console.info(index+":"+resultList[index]);//form-control select2
		                	}
		                }
		            	**/
		            	var htmlContent = "";
		            	htmlContent = htmlContent + "<select class='form-control' name='composeCompare[0].protoKey'>";
		            	htmlContent = htmlContent + "<option value=''>请选择字段</option> ";
		                if(resultMap != null){
		                	//遍历List
		                	//for(var index in resultList){
		                	//	htmlContent = htmlContent + "<option value='"+resultList[index]+"' {{if type==='"+resultList[index]+"'}}selected{{/if}}>"+resultList[index]+"</option> ";
		                	//}
		                	
		                	//遍历map
		                	$.each(resultMap, function(key, value) {
		                		htmlContent = htmlContent + "<option value='"+key+"' {{if type==='"+key+"'}}selected{{/if}}>"+value+"</option> ";
		                	})
		                }
		            	htmlContent = htmlContent + "</select> ";
		            	htmlContent = htmlContent + "";
		            	$("#keyContent").html(htmlContent);
		            }
		        })　　　
    		})  
    	});
    	
    	
    	//数据表导出
    	function tableOutput(){
    		
			var exportTableName = $("#protoNameSelect").val();
        	
        	if(exportTableName == ""){
        		$.modal.alertWarning("请先选择数据表名称！");
        		return;
        	}
        	
    		$.modal.confirm("确定导出数据表" + exportTableName + "的所有数据吗？", function() {
                //$.modal.loading("正在导出数据，请稍候...");
                
                window.location.href = 'http://' + ipm + ':8081/protoTable/exportTableData?tableName=' + encodeURI(exportTableName);
                
                /**
                $.ajax({
                	url: 'http://' + ipm + ':8081/protoTable/exportTableData',
                	type: 'POST',
                	//contentType: 'application/json',
                	//dataType: 'json',
                	data: {"tableName":exportTableName},
                	success: function (response) {
                		if(response.message == "success"){//成功
                            $.modal.closeAll();
                            $.modal.alertSuccess("导出成功！");
                		}else{
                			$.modal.closeAll();
                             $.modal.alertError("导出失败！");
                		}
                	}
                });
                **/
                
            });
    	}
    	
    	//数据表导入
    	function tableInput(){
    		
			var exportTableName = $("#protoNameSelect").val();
        	
        	if(exportTableName == ""){
        		$.modal.alertWarning("请先选择数据表名称！");
        		return;
        	}
        	
    		var queryParam = {
    				"tableName": exportTableName
    			};
    		
    		//var queryParamData = JSON.stringify(queryParam);
    		
            var currentId = 'importTpl';
            var _width = "400";
            var _height = "230";
            top.layer.open({
                type: 1,
                area: [_width + 'px', _height + 'px'],
                fix: false,
                //不固定
                maxmin: true,
                shade: 0.3,
                title: '导入表数据',
                content: $('#' + currentId).html(),
                btn: ['<i class="fa fa-check"></i> 导入', '<i class="fa fa-remove"></i> 取消'],
                // 弹层外区域关闭
                shadeClose: true,
                btn1: function(index, layero){
                    var file = layero.find('#file').val();
                    if (file == '' || (!$.common.endWith(file, '.txt'))){
                        $.modal.msgWarning("请选择后缀为 “txt”的文件。");
                        return false;
                    }
                    var index = top.layer.load(2, {shade: false});
                    $.modal.disable();
                    
                    var formData = new FormData(layero.find('form')[0]);
                    formData.append("tableName",exportTableName);
                    
                    $.ajax({
	                	url: 'http://' + ipm + ':8081/protoTable/importTableData',
	                	type: 'POST',
	                	cache: false,
                        contentType: false,
                        processData: false,
	                	data: formData,
	                	success: function (response) {
	                		if(response.message == "success"){//成功
	                			$.modal.close(index);
                                $.modal.closeAll();
                                $.modal.alertSuccess("导入成功！");
	                		}else{
	                			 $.modal.close(index);
                                 $.modal.enable();
                                 $.modal.alertError("导入失败！");
	                		}
	                		// console.log(response);
	                	},
	                	complete: function () {
                        	layero.find('#file').val('');
                        }
	                });
                }
            });
    	}
    	
    </script>
</body>
</html>
<!-- 
	<option value="eq">等于</option>
	<option value="gt">大于</option>
	<option value="lt">小于</option>
	<option value="ge">大于等于</option>
	<option value="le">小于等于</option>
	<option value="between">区间</option>
 -->
<!-- 比较类型 -->
<script id="oprType" type="text/x-jquery-tmpl">
<div>
<select class='form-control' name='composeCompare[${index}].oprType'>
	<option value="">请选择</option>
	<option value="eq" {{if type==='eq'}}selected{{/if}}>等于</option>
	<option value="gt" {{if type==='gt'}}selected{{/if}}>大于</option>
	<option value="lt" {{if type==='lt'}}selected{{/if}}>小于</option>
	<option value="ge" {{if type==='ge'}}selected{{/if}}>大于等于</option>
	<option value="le" {{if type==='le'}}selected{{/if}}>小于等于</option>
	<option value="between" {{if type==='between'}}selected{{/if}}>区间</option>
</select>
</div>
</script>

<!-- 字段内容 -->
<script id="keyContent" type="text/x-jquery-tmpl">

<select class='form-control' name='composeCompare[0].protoKey'>
    <option value="">协议字段未选</option>
</select>

</script>

<!-- 导入区域 -->
<script id="importTpl" type="text/template">
<form enctype="multipart/form-data" class="mt20 mb10">
	<div class="col-xs-offset-1">
		<input type="file" id="file" name="file"/>
		<font color="red" class="pull-left mt10">
			提示：仅允许导入“txt”格式文件！
		</font>
	</div>
</form>
</script>